package com.lxp.tksys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxp.tksys.common.CustomException;
import com.lxp.tksys.dto.SetmealDto;
import com.lxp.tksys.entity.Dish;
import com.lxp.tksys.entity.Setmeal;
import com.lxp.tksys.entity.SetmealDish;
import com.lxp.tksys.mapper.DishMapper;
import com.lxp.tksys.mapper.SetmealMapper;
import com.lxp.tksys.service.DishService;
import com.lxp.tksys.service.SetmealDishService;
import com.lxp.tksys.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional//操作多张表+事务
    public void saveWithDish(SetmealDto setmealDto) {
        //基本信息
        this.save(setmealDto);                //存入Setmeal
        //只有前端传过来的数据，数据像setmealId需要自己根据对象id查询另一张表获取
        //套餐和菜品关联信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();    //获取setmealDto的id
        setmealDishes.stream().map((item)->{
           item.setSetmealId(setmealDto.getId());
           return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);     //存入 setmealDishes

    }

    //删除套餐、套餐和菜品的关联数据
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //停售的才能删除，status==0，不能删除则抛出异常
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);    //因为是ids所以用in，在in（）集合中的全部都要删除
        queryWrapper.eq(Setmeal::getStatus,1);    //正在售卖的
        int count = this.count(queryWrapper);
        if(count>0){
            throw new CustomException("套餐正在售卖中，不给删");
        }
        //如果可以删除，先删除套餐表setmeal根据ids
        this.removeByIds(ids);
        //在删除关系表-setmealdish,根据SetmealId
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(dishLambdaQueryWrapper);
    }

}
